//
//  ClubForgetPasswordViewController.swift
//  77Club
//
//  Created by Apple on 2024/9/20.
//

import UIKit

class ClubForgetPasswordViewController: ClubBaseViewController, UITextFieldDelegate {

    private let bgView = c_make_ex(UIImageView.self)
        .image("Login_bg").mode(.scaleAspectFill).end()
    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let logoImageView = c_make_ex(UIImageView.self)
        .image("Login_logo").mode(.scaleAspectFill).end()
    private let titleLabel = c_make_ex(UILabel.self)
        .text("修改密码").color("#17181A").font(24.font_semiBold).end()
    private var leftImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    let phoneTextfield = c_make_ex(UITextField.self)
        .bgColor(.white).corner(25).color(.black).font(14.font_medium)
        .placeholder("请输入手机号码").end()
    let codeTextfield = c_make_ex(UITextField.self)
        .bgColor(.white).corner(25).color(.black).font(14.font_medium)
        .placeholder("请输入验证码").end()
    let passwordTextfield = c_make_ex(UITextField.self)
        .bgColor(.white).corner(25).color(.black).font(14.font_medium)
        .placeholder("请输入6~12位密码").end()
    private let sendButton = c_make_ex(UIButton.self)
        .bgImage(UIImage.colorToImage(color: "#FF831A".toColor))
        .bgImage(UIImage.colorToImage(color: "#FFAA61".toColor.alpha(0.5)),state: .disabled)
        .color(.white).color(.white.alpha(0.5), state: .disabled)
        .corner(16).font(13.font_medium).text("获取验证码").end()
    private let sureButton = c_make_ex(UIButton.self)
        .bgImage(UIImage.colorToImage(color: "#FFC99A".toColor), state: .disabled)
        .bgImage(UIImage.colorToImage(color: "#FF831A".toColor))
        .corner(22).color(.white).text("确 定").end()
    
    private var countdownTimer: Timer?
    private var remainingSeconds: Int = 60
    private var backgroundEnterTime: Date?
    
    var sessionid = "" //收到的验证码
    
    //type 0：手机 1：邮箱
    var type: Int = 0 {
        didSet{
            if type == 0 {
 
                self.phoneTextfield.placeholder = "请输入手机号码"
            }else{

                self.phoneTextfield.placeholder = "请输入邮箱"
            }
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            bgView
            backButton
            titleLabel
            logoImageView
            phoneTextfield
            codeTextfield
            passwordTextfield
            sendButton
            sureButton
        }
        
        bgView.fillContainer()
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        titleLabel.leading(16).top(.navi_height + 40)
        logoImageView.trailing(0).top(.statusHeight + 4).height(187).width(142)
        phoneTextfield.leading(16).trailing(16).height(50).top(.navi_height + 118.0.Scale)
        codeTextfield.leading(16).trailing(16).height(50)
        codeTextfield.Top == phoneTextfield.Bottom + 24
        passwordTextfield.leading(16).trailing(16).height(50)
        passwordTextfield.Top == codeTextfield.Bottom + 24
        sendButton.width(100).height(32)
        sendButton.CenterY == codeTextfield.CenterY
        sendButton.Trailing == codeTextfield.Trailing - 8
        sureButton.leading(16).trailing(16).height(44)
        sureButton.Top == passwordTextfield.Bottom + 40
        
        phoneTextfield.style { v in
            v.placehold("#7B7D80".toColor, font: 14.font_medium)
            leftImageView = UIImageView(frame: CGRect(x: 13, y: 16, width: 24, height: 24))
            if type == 0 {
                leftImageView.image = "Login_phone".toImage
            }else{
                leftImageView.image = "Login_email".toImage
            }
            
            let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 56, height: 50))
            leftView.addSubview(leftImageView)
            v.leftView = leftView
            v.leftViewMode = .always
            v.delegate = self
        }
        codeTextfield.style { v in
            v.placehold("#7B7D80".toColor, font: 14.font_medium)
            let leftImageV = UIImageView(frame: CGRect(x: 13, y: 16, width: 24, height: 24))
            leftImageV.image = "Login_auth".toImage
            let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 56, height: 50))
            leftView.addSubview(leftImageV)
            v.leftView = leftView
            v.leftViewMode = .always
            v.delegate = self
        }
        passwordTextfield.style { v in
            v.placehold("#7B7D80".toColor, font: 14.font_medium)
            let leftImageV = UIImageView(frame: CGRect(x: 13, y: 16, width: 24, height: 24))
            leftImageV.image = "Login_password".toImage
            let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 56, height: 50))
            leftView.addSubview(leftImageV)
            v.leftView = leftView
            v.leftViewMode = .always
            v.isSecureTextEntry = true
            v.delegate = self
        }
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        sureButton.isEnabled = false
        
        sendButton.addTarget(self, action: #selector(clickSendButtonButton), for: .touchUpInside)
        sureButton.addTarget(self, action: #selector(clickSureButtonButton), for: .touchUpInside)
        
        NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        updateSureButtonState()
        return true
    }
    
    private func updateSureButtonState(){
        if phoneTextfield.text?.count ?? 0 > 0 && codeTextfield.text?.count ?? 0 > 0 && passwordTextfield.text?.count ?? 0 > 0 {
            sureButton.isEnabled = true
        }else{
            sureButton.isEnabled = false
        }
    }
}

//MARK: action
extension ClubForgetPasswordViewController {

    @objc private func clickSureButtonButton(){
        
        if type == 0 {
            
            guard let phoneNum = phoneTextfield.text, phoneNum.isValidPhoneNumber else {
                "请输入正确的手机号".toast_error
                return
            }
            guard let codeNum = codeTextfield.text, codeNum.count > 0 else {
                "请输入验证码".toast_error
                return
            }
            guard let password = passwordTextfield.text, password.validatePassword() else {
                "请输入正确的密码".toast_error
                return
            }
            
            let dict = ["phone": phoneNum, "code": codeNum, "sessionid": sessionid, "passwd": password]
            Task{
                ToastUtil.show()
                let models = await network.requestSpecial(.editPassword(json: dict))
                ToastUtil.dismiss()
                if models.isSuccess {
                    
                    self.navigationController?.popViewController(animated: true)
                }else{
                    models.errorMessage?.toast_error
                }
            }
        }else{
            
            guard let emailNum = phoneTextfield.text, emailNum.isValidEmail else {
                "请输入正确的邮箱号".toast_error
                return
            }
            guard let codeNum = codeTextfield.text, codeNum.count > 0 else {
                "请输入验证码".toast_error
                return
            }
            guard let password = passwordTextfield.text, password.validatePassword() else {
                "请输入正确的密码".toast_error
                return
            }
            
            let dict = ["email": emailNum, "code": codeNum, "sessionid": sessionid, "passwd": password]
            Task{
                ToastUtil.show()
                let models = await network.requestSpecial(.editPassword(json: dict))
                ToastUtil.dismiss()
                if models.isSuccess {
                    
                    self.navigationController?.popViewController(animated: true)
                }else{
                    models.errorMessage?.toast_error
                }
            }
            
        }
    }
    
    @objc private func clickSendButtonButton(){
        
        if type == 0 {
            guard let phoneNum = phoneTextfield.text, phoneNum.isValidPhoneNumber else {
                "请输入正确的手机号".toast_error
                return
            }
            Task{
                ToastUtil.show()
                let models = await network.request(.sendCode(phone: phoneNum, type: "1"),type: ClubCodeLoginModel.self)
                ToastUtil.dismiss()
                if models.isSuccess, let model = models.model {
                    self.sessionid = model.sessionid
                    self.sendButton.isEnabled = false
                    self.startCountdown()
                }else{
                    models.errorMessage?.toast_error
                }
            }
        }else{
            guard let phoneNum = phoneTextfield.text, phoneNum.isValidEmail else {
                "请输入正确的邮箱号".toast_error
                return
            }
            Task{
                ToastUtil.show()
                let models = await network.request(.sendEmailCode(email: phoneNum),type: ClubCodeLoginModel.self)
                ToastUtil.dismiss()
                if models.isSuccess, let model = models.model {
                    self.sessionid = model.sessionid
                    self.sendButton.isEnabled = false
                    self.startCountdown()
                }else{
                    models.errorMessage?.toast_error
                }
            }
        }
        
    }
}

//MARK: 验证码倒计时
extension ClubForgetPasswordViewController {
    
    func startCountdown() {
        countdownTimer?.invalidate() // Invalidate any existing timer
        remainingSeconds = 60
        sendButton.setTitle("\(remainingSeconds)秒后重发", for: .normal)
        countdownTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCountdown), userInfo: nil, repeats: true)
    }
    
    @objc func updateCountdown() {
        if remainingSeconds > 0 {
            remainingSeconds -= 1
            sendButton.setTitle("\(remainingSeconds)秒后重发", for: .normal)
        } else {
            countdownTimer?.invalidate()
            self.sendButton.isEnabled = true
            sendButton.setTitle("获取验证码", for: .normal)
        }
    }
    
    @objc func appDidEnterBackground() {
            backgroundEnterTime = Date()
        }

    @objc func appWillEnterForeground() {
        if let backgroundEnterTime = backgroundEnterTime {
            let timeInBackground = Date().timeIntervalSince(backgroundEnterTime)
            remainingSeconds -= Int(timeInBackground)
            if remainingSeconds <= 0 {
                remainingSeconds = 0
                countdownTimer?.invalidate()
                self.sendButton.isEnabled = true
                sendButton.setTitle("获取验证码", for: .normal)
            } else {
                sendButton.setTitle("\(remainingSeconds)秒后重发", for: .normal)
            }
        }
    }
}
